package huoshan

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"sync"
	"time"

	ltool "gitee.com/wosylf/ltool"
)

type HsClent struct {
	AccessKeyID     string
	AccessKeySecret string
	RoleTrn         string
	NotifyUrl       string
	Sts             *Credentials
	ExpiredTime     int64 //过期时间12个小时
	Un              sync.Mutex
}

func F新建链接(ak, sk, role, NotifyUrl string) *HsClent {
	return &HsClent{
		AccessKeyID:     ak,
		AccessKeySecret: sk,
		RoleTrn:         role,
		NotifyUrl:       NotifyUrl,
	}
}

func (a *HsClent) F新建人脸识别(name, idcard, returnurl string) (h5body *CreateH5token, err error) {
	sts, err := a.F获取token()
	if err != nil {
		return
	}
	h5body = &CreateH5token{Name: name, IdCard: idcard}
	h5body.StsToken = sts.SessionToken
	h5body.ConfigId, err = a.FH5套餐配置(sts, returnurl)
	if err != nil {
		return
	}
	h5body.BytedToken, err = a.Fh5token(h5body)
	if err != nil {
		return
	}
	h5body.Url = fmt.Sprintf("https://h5-v2.kych5.com/?accessKeyId=%s&secretAccessKey=%s&sessionToken=%s&configId=%s&bytedToken=%s&lng=zh",
		sts.AccessKeyId, sts.SecretAccessKey, sts.SessionToken, h5body.ConfigId, h5body.BytedToken)
	return
}

func (a *HsClent) F获取token() (sts *Credentials, err error) {
	if a.Sts != nil && a.ExpiredTime > time.Now().Unix() {
		sts = a.Sts
		return
	}
	a.Un.Lock()
	defer a.Un.Unlock()
	query1 := make(url.Values)
	query1.Set("RoleTrn", a.RoleTrn)
	query1.Set("RoleSessionName", "just_for_test")
	query1.Set("DurationSeconds", "43200")

	query1.Set("Action", "AssumeRole")
	query1.Set("Version", "2018-01-01")
	by, err := a.F发送请求(http.MethodGet, "https://sts.volcengineapi.com", "sts", nil, query1, nil)
	if err != nil {
		return
	}
	//fmt.Println("bF获取tokenyte,", string(by))
	var resp AssumeRoleResp
	//bm := make(ltool.BodyMap)
	json.Unmarshal(by, &resp)
	sts = resp.Result.Credentials
	a.Sts = sts
	a.ExpiredTime = time.Now().Unix() + 3600*11
	return
}

func (a *HsClent) FH5套餐配置(sts *Credentials, returnurl string) (config_id string, err error) {
	bm := make(ltool.BodyMap)
	bm.Set("req_key", "cert_h5_config_init")
	bm.SetBodyMap("h5_config", func(bm ltool.BodyMap) {
		bm.Set("type", "3").Set("redirect_url", returnurl)
	})
	bm.SetBodyMap("liveness_config", func(bm ltool.BodyMap) {
		bm.Set("ref_source", "1").Set("liveness_type", "motion")
	})
	//下面是回调，感觉不加也行。。。还要解密麻烦
	/* bm.SetBodyMap("callback_info", func(bm ltool.BodyMap) {
		bm.Set("switch", true).Set("url", a.NotifyUrl).Set("block", false).Set("client_name", client_name)
	}) */

	query1 := make(url.Values)
	query1.Set("Action", "CertH5ConfigInit")
	query1.Set("Version", "2022-08-31")
	if sts == nil {
		sts, _ = a.F获取token()
	}
	//bm.Set("sts_token", sts["SessionToken"])
	by, err := a.F发送请求(http.MethodPost,
		"https://visual.volcengineapi.com", "cv", sts,
		query1, []byte(bm.JsonBody()))
	if err != nil {
		return
	}
	var resp CertConfigInitResult
	err = json.Unmarshal(by, &resp)
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	if resp.Code != 10000 {
		err = errors.New(resp.Message)
	}
	config_id = resp.Data.ConfigId
	return
}

func (a *HsClent) Fh5token(body *CreateH5token) (bytedToken string, err error) {
	bm := make(ltool.BodyMap)
	bm.Set("req_key", "cert_h5_token")
	bm.Set("h5_config_id", body.ConfigId)
	bm.Set("sts_token", body.StsToken)
	bm.Set("idcard_no", body.IdCard)
	bm.Set("idcard_name", body.Name)

	query1 := make(url.Values)
	query1.Set("Action", "CertH5Token")
	query1.Set("Version", "2022-08-31")
	by, err := a.F发送请求(http.MethodPost, "https://visual.volcengineapi.com", "cv", nil, query1, []byte(bm.JsonBody()))
	//fmt.Println("by:", string(by))
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	var resp CertTokenResult

	json.Unmarshal(by, &resp)
	if resp.Code == 10000 {
		bytedToken = resp.Data.BytedToken
	} else {
		err = errors.New(resp.Message)
	}
	return
}

func (a *HsClent) F查询人脸结果(id string) (data *CertVerifyQueryData, err error) {
	bm := make(ltool.BodyMap)
	bm.Set("req_key", "cert_pro_verify_query")
	bm.Set("byted_token", id)

	query1 := make(url.Values)
	query1.Set("Action", "CertVerifyQuery")
	query1.Set("Version", "2022-08-31")

	/* sts, _ := F获取token()
	bm.Set("sts_token", sts["SessionToken"]) */
	var by []byte
	by, err = a.F发送请求(http.MethodPost,
		"https://visual.volcengineapi.com", "cv", nil,
		query1, []byte(bm.JsonBody()))
	//fmt.Println("by", string(by))
	var res CertVerifyQueryResult
	json.Unmarshal(by, &res)
	//fmt.Println("认证返回结果", res.Data.Result)
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	data = res.Data
	return
}
